/**  
 * @Title:  UpLoadController.java   
 * @Package com.gtjy.p2p.modules.sys.controllers   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: 吴元森 
 * @date:   2018年4月14日 上午11:42:41   
 * @version V1.0 
 * @Copyright: 2018 吴元森.
 */
package com.platform.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.common.collect.Maps;
import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.dto.Attachments;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IAttachments;
import com.platform.service.IMinioFileService;
import com.platform.utils.HttpContextUtils;
import com.platform.utils.TokenManager;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**   
 * @ClassName:  UpLoadController   
 * @Description:系统统一附件上传   
 * @author: 吴元森 
 * @date:   2018年4月14日 上午11:42:41   
 *     
 * @Copyright: 2018 吴元森.  
 */
@Api(tags= {"COMMON-附件上传服务"})
@Controller
@RequestMapping("fileUpload") 
public class UpLoadController {
	
	@Autowired
	private IAttachments attachmentServices;
	
	@Autowired
	private IMinioFileService fileServerService;
	
	@RequestMapping(value="data",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="分页查询")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ds", value = "数据对象", required = true, dataType = "DataSouce"),
        @ApiImplicitParam(name = "start", value = "页码", required = true, dataType = "int"),
        @ApiImplicitParam(name = "limit", value = "每页显示条数", required = true, dataType = "int")
	})
	public Object selectAll(Attachments atta,
			Integer start,
			Integer limit,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		PageUtil pg = new PageUtil();
		pg.setPageSize(limit);
		pg.setPageIndex(start);
		pg.setParams(BeanUtil.beanToMap(atta));
		return R.success(attachmentServices.selectByMapPaging(pg),pg.getTotal());
	}
	
	/**
	 * @Title: multipicupload   
	 * @Description: 文件上传
	 * @param request
	 * @param response      
	 * void
	 */
	@ApiOperation("单文件上传")
	@ApiLog(value = "单个文件上传",desc="")
	@RequestMapping(value="multipicupload",method=RequestMethod.POST)
	@ResponseBody
	public Object multipicupload(HttpServletRequest request,HttpServletResponse response) {
		Map<String,String> resultMap = Maps.newHashMap();
	    try {
	    	//FileItem 类用来判断是否是普通文本表单域(true)还是一个文件表单字段(false)
	    	MultipartHttpServletRequest multipart = (MultipartHttpServletRequest)request; 
	    	// 获得上传的文件（根据前台的name名称得到上传的文件）  
	    	MultiValueMap<String, MultipartFile> multiValueMap = multipart.getMultiFileMap();  
	    	List<MultipartFile> file = multiValueMap.get("file");  
	    	String filePath = request.getParameter("bucket");
	    	//创建文件夹 如果不存在
	    	if(!file.isEmpty()){
	    		//在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹  
	    		for(MultipartFile  m : file) {
	    			upload(request,filePath,m,resultMap);
	    		}
	    	}
	    	return R.success(resultMap);
    	} catch (Exception e) {
    		return R.fail(e);
        }
	}
	
	@ApiLog(value = "批量上传附件",desc = "")
	@ApiOperation("批量文件上传")
	@RequestMapping(value="multipicuploadBatch",method=RequestMethod.POST)
	@ResponseBody
	public Object multipicuploadBatch(HttpServletRequest request,HttpServletResponse response) {
		Map<String,String> resultMap = Maps.newHashMap();
	    try {
	    	//FileItem 类用来判断是否是普通文本表单域(true)还是一个文件表单字段(false)
	    	MultipartHttpServletRequest multipart = (MultipartHttpServletRequest)request; 
	    	// 获得上传的文件（根据前台的name名称得到上传的文件）  
	    	MultiValueMap<String, MultipartFile> multiValueMap = multipart.getMultiFileMap();  
	    	List<MultipartFile> file = multiValueMap.get("file");  
	    	String filePath = request.getParameter("bucket");
	    	//创建文件夹 如果不存在
	    	if(!file.isEmpty()){
	    		//在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹  
	    		for(MultipartFile  m : file) {
	    			upload(request,filePath,m,resultMap);
	    		}
	    	}  
	    	return R.success(resultMap);
    	} catch (Exception e) {
    		return R.fail(e);
        }
	}
	
	/**
	 * @Title: upload   
	 * @Description: 文件上传
	 * @param request
	 * @param filePath
	 * @param m
	 * @param printWriter
	 * @throws Exception      
	 * void
	 */
	private void upload(HttpServletRequest request, String filePath,MultipartFile m,Map<String,String> eru)throws Exception {
		//上传完成以后的文件名
        String saveFileName = fileServerService.upload(filePath, m);
        
        //保存到附件表
        Attachments attachment = new Attachments();
        attachment.setQquuid(request.getParameter("qquuid"));
        attachment.setQqfilename(request.getParameter("qqfilename"));
        attachment.setQqtotalfilesize(Double.valueOf(request.getParameter("qqtotalfilesize")));
        attachment.setName(request.getParameter("qqfilename"));
        attachment.setFilepath(filePath+"|"+saveFileName);
        attachment.setCreater(TokenManager.getUserName(HttpContextUtils.getAccessToken()));
        attachment.setCreatetime(new Date(System.currentTimeMillis()));
        attachmentServices.insert(attachment);
        
        eru.put("path",attachment.getFilepath());
        eru.put("name",attachment.getName());
    }
	
	
	@SuppressWarnings("unused")
	private void uploadBatch(HttpServletRequest request, String filePath,MultipartFile m,Map<String,String> eru)throws Exception {
		//上传完成以后的文件名
        String saveFileName = fileServerService.upload(filePath, m);
        
        //保存到附件表
        Attachments attachment = new Attachments();
        attachment.setQquuid(request.getParameter("qquuid"));
        attachment.setQqfilename(request.getParameter("qqfilename"));
        attachment.setQqtotalfilesize(Double.valueOf(request.getParameter("qqtotalfilesize")));
        attachment.setName(request.getParameter("qqfilename"));
        attachment.setFilepath(filePath+"|"+saveFileName);
        attachment.setCreater(TokenManager.getUserName(HttpContextUtils.getAccessToken()));
        attachment.setCreatetime(new Date(System.currentTimeMillis()));
        attachmentServices.insert(attachment);
        
        eru.put("path",attachment.getFilepath());
        eru.put("name",attachment.getName());
    }
	
	/**
	 * @Title: deletepicupload   
	 * @Description: 文件删除
	 * @param request
	 * @param response
	 * @return      
	 * Object
	 */
	@ApiOperation("附件删除")
	@ApiLog(value="删除附件信息",desc="公共模块文件删除")
	@RequestMapping(value="deletepicupload",method= {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object deletepicupload(HttpServletRequest request,HttpServletResponse response) {
		String qquuid = request.getParameter("qquuid");
		return attachmentServices.deleteByPrimaryKey(qquuid);
	}
	
	@ApiOperation("获取附件列表")
	@RequestMapping(value="attachmentData",method= {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object attachmentData(Attachments attach,Integer start,Integer limit) {
		PageUtil pageUt = new PageUtil(start, limit, BeanUtil.beanToMap(attach));
		return R.success(attachmentServices.selectByMapPaging(pageUt), pageUt.getTotal());
	}

	@ApiOperation("查看附件")
	@RequestMapping(value="lookAttachment",method= {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object lookAttachment(String ids) {
		return attachmentServices.selectByParam(ids);
	}
	
	@ApiOperation("基于minio文件下载")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "bucket", value = "存储桶名称", required = true, dataType = "String"),
        @ApiImplicitParam(name = "fileId", value = "文件名", required = true, dataType = "String")
	})
	@GetMapping("file/v1/download/{bucket}/{fileId}")
	@ResponseBody
	public void download(@PathVariable String bucket, @PathVariable String fileId,HttpServletResponse response) throws Exception{
		fileServerService.download(bucket, fileId, response);
	}
	
	@GetMapping("file/v1/downloadSaveLocal/{bucket}/{fileId}")
	@ResponseBody
	public R<?> downloadSaveLocal(@PathVariable String bucket, @PathVariable String fileId,HttpServletResponse response) throws Exception{
		return R.success(fileServerService.downSaveLocal(bucket, fileId, response));
	}
	
	@ApiOperation("基于minio文件删除")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "bucket", value = "存储桶名称", required = true, dataType = "String"),
        @ApiImplicitParam(name = "fileId", value = "文件名", required = true, dataType = "String")
	})
	@GetMapping("file/v1/remove/{bucket}/{fileId}")
	@ResponseBody
	public R<?> remove(@PathVariable String bucket, @PathVariable String fileId) throws Exception{
		fileServerService.delete(bucket, fileId);
		return R.success();
	}
	
	@ApiOperation("基于minio文件预览")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "bucket", value = "存储桶名称", required = true, dataType = "String"),
        @ApiImplicitParam(name = "fileName", value = "文件名", required = true, dataType = "String")
	})
	@GetMapping("file/v1/preivew/{bucket}/{fileName}")
	@ResponseBody
	public R<?> preview(@PathVariable String bucket,@PathVariable String fileName) {
		return R.success(fileServerService.preview(bucket, fileName));
	}
	
	
}
